//
//  ReflectMoneyController.m
//  cooba-iOS
//
//  Created by 郭四虎 on 16/9/9.
//  Copyright © 2016年 YouKu. All rights reserved.
//

#import "ReflectMoneyController.h"

@interface ReflectMoneyController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UILabel *idLB;
@property (weak, nonatomic) IBOutlet UIButton *noti;
@property (weak, nonatomic) IBOutlet UITextField *name;
@property (weak, nonatomic) IBOutlet UITextField *reflectMoney;
@property (weak, nonatomic) IBOutlet UILabel *remain;
@property (weak, nonatomic) IBOutlet UIButton *confirm;

@property (strong, nonatomic) IBOutlet UIView *confirmView;
@property (weak, nonatomic) IBOutlet UITextField *pwd;

@end

@implementation ReflectMoneyController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view from its nib.
    _noti.layer.borderWidth = 1;
    _noti.layer.borderColor = RGBcolor(43, 170, 250).CGColor;
    
    [_reflectMoney addTarget:self action:@selector(changed) forControlEvents:UIControlEventEditingChanged];
    [_name becomeFirstResponder];
    _idLB.text = [[Myuser sharedUser].login_id stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
    _remain.text = [NSString stringWithFormat:@"可用余额%@元",_money];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    
    if ([_pwd isFirstResponder]) {
        NSDictionary *userInfo = [aNotification userInfo];
        NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
        CGRect keyboardRect = [aValue CGRectValue];
        int height = keyboardRect.size.height;
        
        CGRect rect = _confirmView.frame;
        rect.origin.y = -height;
        _confirmView.frame = rect;
    }
    
}

- (void)keyboardWillHide:(NSNotification *)aNotification
{
    CGRect rect = _confirmView.frame;
    
    if (_confirmView.y) {
        rect.origin.y = 0;
        _confirmView.frame = rect;
    }
}

- (IBAction)confirmPWD:(id)sender {
    
    NSDictionary *parameter = @{@"login_id":[Myuser sharedUser].login_id,@"password":[MyMD5 md5:_pwd.text]};
    
    [MyAFN POST:CHECKPWD parameters:parameter block:^(id responseObject) {
        
        NSDictionary *dic = responseObject;
        if ([[dic objectForKey:@"status"]integerValue]) {
            
                [MyRedPacket reflectPacket:_reflectMoney.text name:_name.text back:^(BOOL suc, NSDictionary *dic) {
                    
                    [_confirmView removeFromSuperview];
                    
                    if (suc) {
            
                        self.back(dic[@"money"]);
                        [self.view performSelector:@selector(Message:) withObject:@"提现申请成功，请等待" afterDelay:0.5];
                        [self.navigationController performSelector:@selector(popViewControllerAnimated:) withObject:@(YES) afterDelay:1.5];
                    }else{
                        
                        if (dic[@"msg"]) {
                            [self.view performSelector:@selector(Message:) withObject:dic[@"msg"] afterDelay:0.5];
                        }else{
                            [self.view Message:@"申请失败，请确认填写信息"];
                        }
                    }
                }vc:self];
        }else{
            
            [_confirmView removeFromSuperview];
            _pwd.text = @"";
            [self.view performSelector:@selector(Message:) withObject:@"密码错误" afterDelay:0.5];
        }
        
    } error:^(NSError *error) {
        
    } fromController:nil];
}
- (IBAction)cancle:(id)sender {
    
    [_confirmView removeFromSuperview];
}
- (IBAction)showNoti:(UIButton *)sender {
    
    MyView *v = [[MyView alloc]initWithFrame:SCREEN startPoint:[sender.superview convertPoint:CGPointMake(sender.center.x, sender.center.y+30) toView:self.view] msg:@"        用于打款时校验该用户的手机号是否与用户姓名匹配。\n        请填写支付宝绑定的身份证姓名，谨慎填写，若校验不通过，申请提现将被打回"];
    [self.view addSubview:v];
}
- (IBAction)confirm:(id)sender {
    NSLog(@"aaa");
    
    [self.view endEditing:YES];
    
    if (_reflectMoney.text.floatValue > _money.floatValue) {
        return;
    }
    
    if (!_name.text.length) {
        
        [self.view Message:@"请填写姓名"];
        return;
    }
    
    if (_reflectMoney.text.floatValue < _drawMoney) {
        
        [self.view Message:@"最低提现金额为10元"];
        return;
    }
    
    _confirmView.width = WIDTH;
    _confirmView.height = HEIGHT;
    [WINDOW addSubview:self.confirmView];
}
- (void)changed
{

    if (_reflectMoney.text.length) {
        
        if (_reflectMoney.text.floatValue > _money.floatValue) {
            
            _remain.text = @"金额超出可提现余额";
            _remain.textColor = [UIColor redColor];
            
            _confirm.backgroundColor = [UIColor lightGrayColor];
            [_confirm setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
            _confirm.enabled = NO;
        }else{
            _remain.text = [NSString stringWithFormat:@"可用余额%@元",_money];
            _remain.textColor = [UIColor darkGrayColor];
            
            _confirm.backgroundColor = RGBcolor(43, 170, 250);
            [_confirm setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            _confirm.enabled = YES;
        }
        
    }else{
        _confirm.backgroundColor = [UIColor lightGrayColor];
        [_confirm setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        _confirm.enabled = NO;
    }
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField == _reflectMoney) {
        
        [UIView animateWithDuration:0.2 animations:^{
            
            self.view.frame = CGRectMake(0, -150, WIDTH, HEIGHT);
        }];
    }
    
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField == _reflectMoney) {
        
        [UIView animateWithDuration:0.2 animations:^{
            self.view.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
        }];
    }
}

- (BOOL)stringContainsEmoji:(NSString *)string{
    __block BOOL returnValue = NO;
    
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                                const unichar hs = [substring characterAtIndex:0];
                                if (0xd800 <= hs && hs <= 0xdbff) {
                                    if (substring.length > 1) {
                                        const unichar ls = [substring characterAtIndex:1];
                                        const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                                        if (0x1d000 <= uc && uc <= 0x1f77f) {
                                            returnValue = YES;
                                        }
                                    }
                                } else if (substring.length > 1) {
                                    const unichar ls = [substring characterAtIndex:1];
                                    if (ls == 0x20e3) {
                                        returnValue = YES;
                                    }
                                    
                                } else {
                                    if (0x2100 <= hs && hs <= 0x27ff) {
                                        returnValue = YES;
                                    } else if (0x2B05 <= hs && hs <= 0x2b07) {
                                        returnValue = YES;
                                    } else if (0x2934 <= hs && hs <= 0x2935) {
                                        returnValue = YES;
                                    } else if (0x3297 <= hs && hs <= 0x3299) {
                                        returnValue = YES;
                                    } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                                        returnValue = YES;
                                    }else if (hs == 0x200d){
                                        returnValue = YES;
                                    }
                                }
                            }];
    
    return returnValue;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    
    if (textField == _name) {
        
        if ([self stringContainsEmoji:string]) {
            
            return NO;
        }else{
            return YES;
        }
//        NSString *str =@"^[\u4e00-\u9fa5]+$";
//        NSPredicate* emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", str];
//        if ([emailTest evaluateWithObject:string]) {
//            return YES;
//        }else{
//            return NO;
//        }
    }
    
    if(textField == _reflectMoney)
    {
        NSCharacterSet *cs;
    
        cs = [[NSCharacterSet characterSetWithCharactersInString:@".0123456789"] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        BOOL basicTest = [string isEqualToString:filtered];
        if(!basicTest)
        {
            
            return NO;
        }else{
            
            if ([string isEqualToString:@"."] && [textField.text containsString:@"."]) {
                return NO;
            }
            if ([textField.text containsString:@"."]&&range.location - [textField.text rangeOfString:@"."].location > 2) {
                
                return NO;
            }
        }
    }
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITouch *tou = [touches anyObject];
    if (tou.view == self.view) {
        
        [self.view endEditing:YES];
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
